package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Program: day57-leadnews
 * @Description:
 * @Data: 2022/7/26 20:23
 **/
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1:参数校验
        //判断 用户名 密码 是否为空
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"请输入用户名或密码");
        }
        //2:根据用户名查询用户信息
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (adUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户名或密码错误");
        }
        //判断用户状态是否为9
        if (9 != adUser.getStatus().intValue()){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //3:获取数据库密码和盐，匹配密码
        String password = adUser.getPassword();//数据库中加密后的密码
        String salt = adUser.getSalt();
        //对用户输入的密码进行加密
        String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        //判读加密后的密码与数据库中的密码是否一致
        if (!password.equals(newPwd)){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4:修改登录时间
        adUser.setLoginTime(new Date());
        updateById(adUser);
        //5:颁发token jwt 令牌
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        //用户信息返回Vo
        AdUserVO adUserVO = new AdUserVO();
        //将adUser类中的属性复制到adUserVO类中
        BeanUtils.copyProperties(adUser,adUserVO);
        //6:返回结果（JWT）
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",adUserVO);
        return ResponseResult.okResult(map);
    }
}
